local hx__tuxi = fk.CreateSkill({
  name = "hx__tuxi",
})


hx__tuxi:addEffect(fk.AfterCardsMove, {
  anim_type = "control",
  times = function (self, player)
    return 4 - player:usedSkillTimes(hx__tuxi.name, Player.HistoryTurn)
  end,
  can_trigger = function(self, event, target, player, data)
    ---@type string
    local skillName = hx__tuxi.name
    if player:hasSkill(skillName) and player.phase ~= Player.NotActive
    and player:usedSkillTimes(skillName, Player.HistoryTurn) < 4 then
      local ids = {}
      for _, move in ipairs(data) do
        if move.to == player and move.toArea == Card.PlayerHand and move.skillName ~= skillName then
          for _, info in ipairs(move.moveInfo) do
            if table.contains(player:getCardIds("h"), info.cardId) then
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end
      ids = player.room.logic:moveCardsHoldingAreaCheck(ids)
      if #ids > 0 then
        event:setCostData(self, ids)
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local _, ret = player.room:askToUseActiveSkill(player,{
      skill_name = "hx__tuxi_active",
      prompt = "#hx__tuxi",
      extra_data = { optional_cards = event:getCostData(self) }
    })
    if ret then
      player.room:sortByAction(ret.targets)
      event:setCostData(self, { cards = ret.cards, to = ret.targets })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    ---@type string
    local skillName = hx__tuxi.name
    local room = player.room
    local costData = event:getCostData(self)
    local tos = costData.to
    room:moveCardTo(costData.cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, skillName, nil, true, player)
    for _, to in ipairs(tos) do
      if player.dead then break end
      if not to:isKongcheng() then
        local cid = room:askToChooseCard(player, { target = to, flag = "h", skill_name = skillName })
        room:obtainCard(player, cid, false, fk.ReasonPrey, player, skillName)
      end
    end
  end,
})


return hx__tuxi
